package com.cat.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.cat.yygh.common.exception.YyghException;
import com.cat.yygh.hosp.repository.ScheduleRepository;
import com.cat.yygh.hosp.service.DepartmentService;
import com.cat.yygh.hosp.service.HospitalService;
import com.cat.yygh.hosp.service.ScheduleService;
import com.cat.yygh.model.hosp.BookingRule;
import com.cat.yygh.model.hosp.Department;
import com.cat.yygh.model.hosp.Hospital;
import com.cat.yygh.model.hosp.Schedule;
import com.cat.yygh.mq.RabbitService;
import com.cat.yygh.vo.hosp.BookingScheduleRuleVo;
import com.cat.yygh.vo.hosp.ScheduleOrderVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    private ScheduleRepository scheduleRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private DepartmentService departmentService;
    @Override
    public void saveSchedule(Map<String, Object> stringObjectMap) {
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(stringObjectMap), Schedule.class);
        Schedule scheduleExist = scheduleRepository.findByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        if (scheduleExist == null) {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
        } else {
            schedule.setCreateTime(scheduleExist.getCreateTime());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(scheduleExist.getIsDeleted());

            schedule.setId(scheduleExist.getId());
        }
        scheduleRepository.save(schedule);
    }

    @Override
    public Page<Schedule> findSchedule(Map<String, Object> stringObjectMap) {
        Integer limit = Integer.parseInt((String) stringObjectMap.get("limit"));
        Integer page = Integer.parseInt((String) stringObjectMap.get("page"));
        String hoscode = (String) stringObjectMap.get("hoscode");
        String depcode = (String) stringObjectMap.get("depcode");
        PageRequest pageRequest = PageRequest.of(page, limit);

        Schedule schedule = new Schedule();
        schedule.setHoscode(hoscode);
        schedule.setDepcode(depcode);
        Example<Schedule> scheduleExample = Example.of(schedule);

        return scheduleRepository.findAll(scheduleExample, pageRequest);
    }

    @Override
    public void removeSchedule(Map<String, Object> stringObjectMap) {
        String hoscode = (String) stringObjectMap.get("hoscode");
        String hosScheduleId = (String) stringObjectMap.get("hosScheduleId");
        Schedule schedule = scheduleRepository.findByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (schedule != null) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    @Override
    public Map<String, Object> page(long page, long limit, String hoscode, String depcode) {
        //1.根据医院科室编号查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);;
        //2.根据日期进行分组
        Aggregation aggregation = Aggregation.newAggregation(
                //查询出来
                Aggregation.match(criteria),
                //分组
                Aggregation.group("workDate")
                        //select worker  ...group by **
                        .first("workDate").as("workDate")
                        //3 统计号源数量
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //根据时间字段仅限排序
                Aggregation.sort(Sort.Direction.ASC, "workDate"),
                //4 实现分页
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );
        /** 调用方法执行查询
         *   aggregation 表示聚合条件
         *   inputType  表示输入类型  
         *   outputType 表示输出类型 封装聚合后的信息
         */
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        //当前页对应的排班列表数据
        List<BookingScheduleRuleVo> mappedResults = aggregate.getMappedResults();

        //分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg,
                        Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();
        //把日期对应星期获取
        for (BookingScheduleRuleVo mappedResult : mappedResults) {
            //获取时间
            Date workDate = mappedResult.getWorkDate();
            String dayDate = this.getDayOfWeek(new DateTime(workDate));
            mappedResult.setDayOfWeek(dayDate);
        }
        //封装返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("list", mappedResults);
        map.put("total", total);
        //获取医院名称
        Hospital hoospitalByHoscode = hospitalService.getHoospitalByHoscode(hoscode);
        String hosname = hoospitalByHoscode.getHosname();
        //其他基础数据
        HashMap<Object, Object> baseMap = new HashMap<>();
        baseMap.put("hosname", hosname);
        map.put("baseMap", baseMap);
        return map;
    }

    //根据医院编号 、科室编号和工作日期，查询排班详细信息
    @Override
    public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {
        List<Schedule> schedule = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode,new DateTime(workDate).toDate());
        //把得到list集合遍历，向设置其他值：医院名称、科室名称、日期对应星期
        schedule.stream().forEach(schedule1 -> {
            //把数据进行封装
            this.packageSchedule(schedule1);
        });
        return schedule;
    }
    //查询排班分页
    @Override
    public Map<String, Object> getSchedulePage(String hoscode, String depcode, Integer pageNum, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        //获取预约规则
        Hospital hospital = hospitalService.getHoospitalByHoscode(hoscode);
        if (hospital == null){
            throw new YyghException(20001,"该医院信息不存在");
        }
        //获取预约规则
        BookingRule rule = hospital.getBookingRule();
        //获取【当前页】可预约日期以及 分页数据【页码，页数，总条数】
        IPage iPage = this.getListDate(pageNum,pageSize, rule);
        //【当前页】可预约日期
        List<Date> dateList = iPage.getRecords();
        //获取可预约日期科室剩余预约数
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);
        //分株查询条件
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")//分组字段
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        //分页聚合查询数据
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        //=============================================================MongoDb聚合结果集
        List<BookingScheduleRuleVo> scheduleVoList = aggregationResults.getMappedResults();
        //合并数据 将统计数据ScheduleVo根据“安排日期”合并到BookingRuleVo
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        //将数据转化成键名==>值类型数据
        if(!CollectionUtils.isEmpty(scheduleVoList)) {                                              //键名========>键值
            scheduleVoMap = scheduleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }
        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        //当前页所有的时间集合 长度
        int len=dateList.size();
        //遍历当前时间集合
        for (int i = 0; i < len; i++) {
            //获取时间集合数据
            Date date = dateList.get(i);
            //将时间传入获取聚合的数据
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            if(null == bookingScheduleRuleVo) { // 说明当天没有排班医生
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            //可预约日期
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期为周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if(i == len-1 && pageNum == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if(i == 0 && pageNum == 1) {
                DateTime stopTime = this.getDateTime(new Date(), rule.getStopTime());
                System.out.println(stopTime);
                System.out.println(stopTime.isBeforeNow());
                if(stopTime.isBeforeNow()) {
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }
        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHoospitalByHoscode(hoscode).getHosname());
        //科室
        Department department =departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", rule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", rule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }

    @Override
    public Schedule getById(String id) {
        Schedule schedule = scheduleRepository.findById(id).get();
        return this.packageSchedule(schedule);
    }

    @Override
    public ScheduleOrderVo getScheduleById(String scheduleId) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //从源对象复制到目标对象v
        BeanUtils.copyProperties(schedule,scheduleOrderVo);
        //设置医院名称
        Hospital hospital = hospitalService.getHoospitalByHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospital.getHosname());
        //设置科室名称
        Department department = departmentService.getDepartment(schedule.getHoscode(), schedule.getDepcode());
        scheduleOrderVo.setDepname(department.getDepname());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        /*退号时间*/
        String quitTime = hospital.getBookingRule().getQuitTime();
        /*退号截至时间*/
        Integer quitDay = hospital.getBookingRule().getQuitDay();
        DateTime dateTime = new DateTime(schedule.getWorkDate()).plusDays(quitDay);
        DateTime quitTimes = this.getDateTime(dateTime.toDate(), quitTime);
        //预约退号截至时间
        scheduleOrderVo.setQuitTime(quitTimes.toDate());
        //当天停止挂号时间
        Date workDate = schedule.getWorkDate();
        String stopTimeString = hospital.getBookingRule().getStopTime();
        DateTime stopTime = this.getDateTime(workDate, stopTimeString);
        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }

    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        //主键一致就是更新
        scheduleRepository.save(schedule);
    }

    @Override
    public boolean updateAvailableNumber(String scheduleId, Integer availableNumber) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();

        schedule.setAvailableNumber(availableNumber);
        schedule.setUpdateTime(new Date());

        scheduleRepository.save(schedule);
        return true;
    }

    @Override
    public void cancelSchedule(String scheduleId) {
        Schedule schedule=scheduleRepository.findByHosScheduleId(scheduleId);
        schedule.setAvailableNumber(schedule.getAvailableNumber()+1);
        scheduleRepository.save(schedule);
    }

    //获取可预约日期分页数据
    private IPage getListDate(Integer pageNum, Integer pageSize, BookingRule rule) {
        //当天放号时间
        DateTime releaseTime = this.getDateTime(new Date(),rule.getReleaseTime());
        //预约周期
        int cycle = rule.getCycle();
        //如果当天放号时间已过，则预约周期后一天为即将放号时间，周期加1
        //isBeforeNow比当前时间 返回Boolean
        if(releaseTime.isBeforeNow()) cycle += 1;
        //可预约【所有】日期，最后一天显示即将放号倒计时
        List<Date> list = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            //计算当前预约日期
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            list.add(new DateTime(dateString).toDate());
        }
        //日期分页，由于预约周期不一样，页面一排最多显示7天数据，多了就要分页显示
        List<Date> pageDateList = new ArrayList<>();
        //起始位置
        int start = (pageNum-1)*pageSize;
        //终止位置
        int end = start+pageSize;
        if (end>list.size()) end = list.size();
        //【当前页】的所有日期
        for (int i = start; i < end; i++) {
            pageDateList.add(list.get(i));
        }
        //创建分页对象
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Date> page =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<Date>(pageNum, pageSize, list.size());
        page.setRecords(pageDateList);
        return page;
    }

    /**
    * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
    */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    //封装排班详情其他值 医院名称、科室名称、日期对应星期
    private Schedule packageSchedule(Schedule schedule1) {
        //设置医院名称
        schedule1.getParam().put("hosname", hospitalService.getHoospitalByHoscode(schedule1.getHoscode()).getHosname());
        //设置科室名称
        schedule1.getParam().put("depname", departmentService.getDepName(schedule1.getHoscode(), schedule1.getDepcode()));
        //设置日期
        schedule1.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(schedule1.getWorkDate())));
        return schedule1;
    }

    /**
     * 8 * 根据日期获取周几数据
     * 9 * @param dateTime
     * 10 * @return
     * 11
     */
    private String getDayOfWeek(DateTime dateTime) {
        //声明一个返回的参数
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
                break;
            default:
                break;
        }
        return dayOfWeek;
    }
}
